<template>
  <Dialog v-model="dialogVisible" title="修改上级代理" :scroll="true">
    <el-form ref="formRef" v-loading="formLoading" :model="queryParams" label-width="70px">
      <el-form-item label="代理名称" prop="agentName">
        <el-input
          v-model="queryParams.agentName"
          placeholder="请输入代理名称"
          class="!w-240px"
          v-loading="formLoading"
        >
          <template #append>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /></el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <el-table :data="list">
      <el-table-column label="代理名称" align="left">
        <template #default="scope">
          <div class="flex">
            <el-text truncated>{{ scope.row.agentName }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名|昵称" align="left">
        <template #default="scope">
          <div class="flex" v-if="scope.row.user">
            <div class="w-[48px] h-[48px] m-r-10px">
              <el-image
                :preview-teleported="true"
                :src="scope.row?.user?.avatar"
                class="w-[48px] h-[48px] rounded-4px align-middle"
              />
            </div>

            <el-text truncated>{{ scope.row.user.nickname }}</el-text>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="代理等级" align="center" min-width="80px" prop="agentLevelName" />
      <el-table-column label="权重" align="center" min-width="50px" prop="agentLevel" />

      <el-table-column label="操作" align="center" width="100px">
        <template #default="scope">
          <el-button type="primary" @click="submitForm(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </Dialog>
</template>
<script lang="ts" setup>
import * as AgentUserApi from '@/api/mall/trade/agent/user'

/** 修改上级代理商表单 */
defineOptions({ name: 'UpdateBindUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref()
const formRef = ref() // 表单 Ref

const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  agentName: null
})
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AgentUserApi.getBrokerageUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 打开弹窗 */
const open = async (row: AgentUserApi.AgentUserVO) => {
  resetForm()
  // 设置数据
  formData.value = row
  await getList()

  // formData.value.bindUserId = row.bindUserId
  // // 反显上级代理商
  // if (row.bindUserId) {
  //   await handleGetUser()
  // }
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
/** 修改上级代理商 */
const submitForm = async (row: any) => {
  // 提交请求
  formLoading.value = true
  try {
    // 发起修改
    let data = {
      agentParentId: row.agentId,
      agentId: formData.value.agentId
    }
    await AgentUserApi.updateParentId(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success', true)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    bindUserId: undefined
  }
  formRef.value?.resetFields()
  bindUser.value = undefined
}

/** 查询推广员 */
const bindUser = ref<AgentUserApi.AgentUserVO>()
// const handleGetUser = async () => {
//   if (formData.value.bindUserId == formData.value.id) {
//     message.error('不能绑定自己为代理商')
//     return
//   }
//   formLoading.value = true
//   bindUser.value = await AgentUserApi.getBrokerageUser(formData.value.bindUserId)
//   if (!bindUser.value) {
//     message.warning('推广员不存在')
//   }
//   formLoading.value = false
// }
</script>
